var express = require("express");
var router = express.Router();
let { userModel } = require("../models/userModel") //导入user模型

/* GET users listing. */
//注册
router.post("/resist", async (req, res, next) => {
  let { username, password } = req.body
  if (username != "" && password != "") {
    let old_data = await userModel.find({ username: req.body.username })
    if (old_data.length == 0) {
      let data = await userModel.create(req.body)
      res.send({
        message: '注册成功',
        code: 200,
        data: data
      })
    } else {
      res.send({
        message: '账号已经存在或没有输入',
        code: 201
      })
    }
  } else {
    res.send({
      message: '账号或密码不能为空',
      code: 202
    })
  }

});

//登录

const jwt = require('jsonwebtoken');
// const { TOKEN_KEY } = require('../until/consts');
router.post('/login', async (req, res) => {
  let data = await userModel.find({ username: req.body.username, password: req.body.password })
  if (data.length > 0) {
    // const token = jwt.sign(
    //   { user: data[0]},
    //   TOKEN_KEY,
    //   { expiresIn: 10}
    // );
    res.send({
      code: 200,
      message: '登录成功',
      token: 'Bearer ' + token
    })
  } else {
    res.send({
      code: 201,
      message: '账号或密码错误'
    })
  }
})



//密码令牌



module.exports = router;
